package com.ujiuye.utils;

import com.ujiuye.pojo.Employee;
import com.ujiuye.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private EmployeeService employeeService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("lanjieqi");
        String requestURI = request.getRequestURI();
        String[] openURI = {"auth","login","css","fonts","images","img","js"};
        for (String open : openURI) {
            if (requestURI.contains(open)){
                return true;//方向
            }
        }

        Object loginSession = request.getSession().getAttribute("LOGIN_SESSION");
        if (loginSession!=null){
            return true;
        }
        //没有登录
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("auth".equals(name)){
                    String value = cookie.getValue();
                    String[] split = value.split("==");
                    String username = split[0];
                    String password = split[1];
                    Employee employee = employeeService.getByUserName(username);
                    request.getSession().setAttribute("LOGIN_SESSION",employee);
                    return true;
                }
            }
        }
        response.sendRedirect("/login.html");
        return false;
    }

}
